/*
 * JGO2RDF creates a RDF representation of GAF2 files, which are automatically sourced from GO ftp site.
 * Copyright (C) 2012 Matthew M. Hindle & Artem Lysenko
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package uk.co.jgo2rdf.goa.deligates;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDFS;
import org.apache.log4j.Logger;
import uk.co.jgo2rdf.exception.AccessionNonConformentException;
import uk.co.jgo2rdf.goa.gp2protein.EntityType;
import uk.co.jgo2rdf.rdf.refseq.RefSeqFactory;
import uk.co.jgo2rdf.rdf.refseq.RefSeqTypeUnsupportedException;
import uk.co.jgo2rdf.rdf.refseq.URIs;
import uk.co.jgo2rdf.rdf.sio.SIOVocab;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: mhindle
 * Date: 13/02/12
 * Time: 14:28
 * To change this template use File | Settings | File Templates.
 */
public class RefSeqRDFizer implements EntityRDFizer {

    private static final Logger log = Logger.getLogger(RefSeqRDFizer.class);

    @Override
    public Resource rdfize(Model jenaModel, String accession) throws Exception {
        String copy = accession;

        accession = preProcessAccession(accession);

        if (!RefSeqFactory.isRefSeqId(accession)) {
            if (GeneBankRDFizer.isGeneBank(accession)) {
                log.debug("Sent " + accession + " to GENBANK rdfizer");
                return new GeneBankRDFizer().rdfize(jenaModel, accession);
            } else {
                throw new AccessionNonConformentException(copy + "=processed-to=>" + accession);
            }
        }

        if (accession.length() == 0) {
            throw new AccessionNonConformentException(copy + "=processed-to=>" + accession);
        }

        Resource refseqRecord = RefSeqFactory.getRefSeqRecord(accession);
        Resource refseqIdentifier = RefSeqFactory.getRefSeqRecord(accession);

        Resource record = jenaModel.createResource(URIs.NCBI + accession.trim().toUpperCase(),
                refseqRecord);
        Resource identifier = jenaModel.createResource(refseqIdentifier);

        record.addProperty(SIOVocab.has_attribute, identifier);
        record.addLiteral(RDFS.label, accession);
        identifier.addLiteral(SIOVocab.has_value, accession);
        identifier.addLiteral(RDFS.label, accession + "-id");

        EntityType type = getType(accession);
        if (type.equals(EntityType.DNA)) {
            Resource dna = jenaModel.createResource(SIOVocab.dna);
            refseqRecord.addProperty(SIOVocab.is_about, dna);
            dna.addLiteral(RDFS.label, accession + "-dna");
            return dna;
        } else if (type.equals(EntityType.RNA)) {
            Resource rna = jenaModel.createResource(SIOVocab.rna);
            refseqRecord.addProperty(SIOVocab.is_about, rna);
            rna.addLiteral(RDFS.label, accession + "-rna");
            return rna;
        } else if (type.equals(EntityType.PROTEIN)) {
            Resource protein = jenaModel.createResource(SIOVocab.protein);
            refseqRecord.addProperty(SIOVocab.is_about, protein);
            protein.addLiteral(RDFS.label, accession + "-protein");
            return protein;
        } else {
            Resource entity = jenaModel.createResource(SIOVocab.entity);
            refseqRecord.addProperty(SIOVocab.is_about, entity);
            entity.addLiteral(RDFS.label, accession + "-entity");
            return entity;
        }
    }

    @Override
    public EntityType getType(String accession) throws RefSeqTypeUnsupportedException {
        if (RefSeqFactory.idIsGenomic(accession))
            return EntityType.DNA;
        else if (RefSeqFactory.idIsRNA(accession))
            return EntityType.RNA;
        else if (RefSeqFactory.idIsProtein(accession))
            return EntityType.PROTEIN;
        throw new RefSeqTypeUnsupportedException(accession);
    }

    private static final Pattern regex;

    static {
        StringBuilder options = new StringBuilder("((");
        for (String code : RefSeqFactory.supportedRefSeqTypes) {
            options.append(code + "|");

        }
        options.setLength(options.length() - 1);//trim last pipe off
        options.append(")_\\d+)");
        regex = Pattern.compile(options.toString());
    }

    @Override
    public String preProcessAccession(String accession) {
        accession = accession.trim().toUpperCase();

        int versionIndex = accession.lastIndexOf('.');
        if (versionIndex > -1) {
            accession = accession.substring(0, versionIndex);
        }

        if (regex != null) {
            Matcher match = regex.matcher(accession);
            if (match.find())
                return match.group(1);
        }

        int prefixIndex = accession.lastIndexOf(':');
        if (prefixIndex > -1) {
            accession = accession.substring(prefixIndex + 1, accession.length());
        }

        return accession;
    }
}
